<template>
  <q-page class="q-pa-md wrapBox">
    <div v-loading="loading">
      <div class="nav">
        <el-breadcrumb separator="/">
          <el-image src="/svgs/modelApplication.svg" style="width: 17px;margin: 0 10px 0 0" fit />
          <el-breadcrumb-item>{{ $t('modelService') }}</el-breadcrumb-item>
          <el-breadcrumb-item><span style="color: #333;">{{ $t('trainingAssignments') }}</span></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="datasetBox" style="position: relative">
        <div class="contentBox_title">
          <span>{{ $t('trainingAssignments') }}</span>
        </div>
        <div class="contentBox">
          <div class="searchWrap" style="margin-top: 10px">
            <div>
              <el-input
                v-model.trim="searchName"
                placeholder="搜索训练任务名称或描述"
                spellcheck="false"
                @keyup.enter="filterDataset"
              >
                <template #prepend>
                  <el-select v-model="typeValue" placeholder="全部" style="width: 120px;background-color: #fff">
                    <el-option
                      v-for="item in modelStatusList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="filterDataset"
                    />
                  </el-select>
                </template>
                <template #append>
                  <el-button :icon="Search" @click="filterDataset" />
                </template>
              </el-input>
            </div>
            <div>
              <el-button
                type="primary"
                size="default"
                @click="toCreatePage"
              >{{ $t('newBuilt') }}</el-button>
            </div>
          </div>
          <el-table
            :data="labelAssignData.results"
            stripe
            style="margin-top: 15px"
            :header-cell-style="{
               background: '#f9f9f9',
               color: '#333',
               fontWeight: '500',
               fontSize: '14px',
               textAlign: 'left',
               height: '56px'
            }"
          >
            <el-table-column align="left" prop="title" label="名称" width="180">
              <template #default="scope">
                <el-button
                  :title="scope.row.title"
                  link type="primary"
                  @click="toDetailPage(scope.row.model_id, scope.row.id)"
                >
                 <span class="overFlowEllipsis">{{ scope.row.title }}</span>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="训练状态" width="80" >
              <template #default="scope">
                <div style="display: flex;align-items: center;justify-content: center">
                  <div style="width: 5px;height: 5px;border-radius: 50%;margin-right: 5px" :style="{'backgroundColor': stateToColor(scope.row.status)}"></div>
                  <div :style="{'color': stateToColor(scope.row.status)}">{{ statusToLanguage(scope.row.status) }}</div>
                </div>
              </template>
            </el-table-column>
<!--        <el-table-column align="left" label="作业类型" width="140">训练作业</el-table-column>-->
            <el-table-column align="left" prop="creator_username" label="创建人" width="80"  />
            <el-table-column align="left" prop="create_at" label="创建时间" />
            <el-table-column align="left" prop="model_title" label="算法" />
            <el-table-column align="left" prop="labels" label="操作">
              <template #default="scope">
                <el-button
                  v-show="userStatus?true:scope.row.creator_username == userInfoName"
                  link type="primary"
                  :disabled="(scope.row.status == 'success' || scope.row.status == 'fail') ? true : false" size="small"
                  @click="scope.row.status == 'running' ? stopRunsFun(scope.row.id) : ''">停止</el-button>
                <el-button
                  :disabled="(scope.row.status == 'success' || scope.row.status == 'fail') ? false : true"
                  link type="primary" size="small" @click="$router.push({ name: 'model-manage-create', params: { project_id: projectId } })">克隆</el-button>
                <el-button
                  @click="restartDialog"
                  :disabled="(scope.row.status == 'success') ? true : false"
                  link type="primary" size="small"
                >重启</el-button>
                <el-button
                  v-show="userStatus?true:scope.row.creator_username == userInfoName"
                  link type="primary" size="small"
                  @click="openDeleteBox(scope.row.model_id, scope.row.id)">删除</el-button>
                <!-- 暂时不需要复用功能，不确定后期是否需要 -->
                <!-- <el-button link type="primary" size="small">复用</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="row" style="justify-content: end;margin: 20px 0;" v-if="labelAssignData.results.length > 0">
          <el-pagination
            background
            layout="total, prev, pager, next, sizes, jumper"
            :total="labelAssignData.count"
            :page-sizes="[10, 20, 50]"
            @size-change="sizeChange"
            :current-page="pageData.page"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <el-dialog v-model="restartDialogShow" title="重启训练任务" width="900px" :show-close="false" :close-on-click-modal="false">
      <div class="restartWrap">
        <div class="borderWrap">
          <el-icon class="titleIcon">
            <WarningFilled />
          </el-icon>
          <div class="text">注：重启仅能解决算力导致训练任务失败的问题</div>
        </div>
        <el-form ref="ruleFormRef" :model="restartForm" :rules="restartRules"
                 :label-position="'right'"
                 label-width="120px" class="restartFormBox"
                 status-icon>
          <el-form-item label="集群队列:" prop="queue">
            <el-select v-model="restartForm.queue" class="m-2" placeholder="请选择仓库模型" style="width: 200px;margin-right: 10px;">
              <el-option v-for="item in modelQueuesList" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="训练资源：" class="cpuDataBox" prop="source">
            <template #default>
              <div class="row" style="min-width: 700px;">
                <div class="col">
                  CPU卡数：<el-input
                  placeholder="请输入"
                  spellcheck="false"
                  class="numberInput"
                  oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>32)value=32;if(value<=0)value=null" v-model="restartForm.source.cpu" size="small" style="width: 120px;"></el-input> 卡
                </div>
                <div class="col" style="margin-right: -30px;">
                  内存：<el-input
                  placeholder="请输入"
                  class="numberInput" spellcheck="false"
                  oninput="if(!/^[0-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>1000000000)value=10000000000;if(value<=0)value=null"
                  v-model="restartForm.source.memory" size="small" style="width: 120px;"></el-input> M
                </div>
                <div class="col">
                  GPU卡数：<el-input
                  placeholder="请输入"
                  class="numberInput" spellcheck="false" v-model="restartForm.source.gpu" size="small"
                  style="width: 120px;"></el-input> 卡
                </div>
              </div>
            </template>
          </el-form-item>
          <span class="tip">(请选择合适算力资源，剩余资源：CPUxx核 ，GPUxx核，内存xxG）</span>
          <el-form-item label="自动停止：">
            <template #default>
              <div style="display: flex;flex-direction: row">
                <el-switch v-model="restartForm.is_auto_stop" />
                <transition name="el-zoom-in-top">
                  <div class="colorBox" v-show="restartForm.is_auto_stop">
                    时长：<el-input v-model="restartForm.stop_in_seconds" size="small"  oninput="value=value.replace(/[^\d]/g,'')"
                                   style="width: 60px;"></el-input> 小时
                    <i>作业时间到最大值会强制停止，若训练未完成可能会造成作业失败</i>
                  </div>
                </transition>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="故障自动重启：">
            <template #default>
              <div style="display: flex;flex-direction: row">
                <el-switch v-model="restartForm.is_fail_restart" />
                <transition name="el-zoom-in-top">
                  <div class="colorBox" v-show="restartForm.is_fail_restart">
                    重启次数： <el-select v-model="restartForm.restartNum" class="m-2" placeholder="" size="small" style="width: 100px;">
                    <el-option :label="1" :value="1" />
                    <el-option :label="2" :value="2" />
                    <el-option :label="3" :value="3" />
                  </el-select><i style="margin-left: 5px">设置后无法更改</i>
                  </div>
                </transition>
              </div>
            </template>
          </el-form-item>
          <el-form-item>
            <div style="display: flex;justify-content: flex-end;width: 100%;margin: 0 40px 20px 0">
              <el-button @click="restartDialogForm(ruleFormRef)" style="background-color: #fff">取消</el-button>
              <el-button type="primary" @click="restartDialogSubmitForm(ruleFormRef)">
                重启
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 350px;">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px;">
              <el-icon
                style="color: #ff5656;display: inline-block;vertical-align: middle;margin-top: -3px;font-size: 20px;">
                <WarningFilled />
              </el-icon>
              删除提示
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none">
            <div>确定删除本条数据吗？</div>
            <div>删除后不可恢复，请谨慎操作！</div>
          </q-card-section>
          <q-card-actions align="right" class="text-primary">
            <el-button v-close-popup style="background-color: #FFFFFF">取消</el-button>
            <el-button type="primary" @click="deleteData">确认删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>
  </q-page>
</template>

<script setup lang="ts">

import {ref, computed, shallowRef, onMounted, reactive} from "vue";
import { useRouter } from 'vue-router';
import {getAllRunsList, deleteRuns, stopRuns, getModelQueues} from 'src/api/model'
import { Search } from '@element-plus/icons-vue'
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const loading = ref(false)
const searchName = ref('')
const dialogDeleteData = ref(false)
import { modelStore } from 'src/stores/model';
import {useUserStore} from "stores/user";
const showUserStore = useUserStore()
import { dataSetStore } from 'src/stores/dataSet';
const store=dataSetStore()
const typeValue = ref('');
import { modelStatusList } from 'src/utils/useData';
const labelAssignData = shallowRef(
  {
    "count": 0,
    "next": "",
    "previous": "",
    "results": [
      {
        "id": 0,
        "title": "",
        "status": "",
        "git_vendor": "",
        "creator_username": "",
        "git_uri": "string",
        "create_at": "",
        "description": "string"
      },
    ]
  }
)
const modelQueuesList = ref([]);//存放集群队列
function stateToColor (val:any){
  if (val === 'running') {
    return '#FF9D43';
  } else if (val === 'fail') {
    return '#FF5656';
  } else if (val === 'success') {
    return '#18B99C';
  } else {
    return '无';
  }
}
function statusToLanguage(val:any){
  if (val === 'running') {
    return '运行中';
  } else if (val === 'fail') {
    return '失败';
  } else if (val === 'success') {
    return '已完成';
  } else {
    return '无';
  }
}
getQueues();//获取模型部署队列
//获取模型队列
function getQueues() {
  getModelQueues().then((res: any) => {
    modelQueuesList.value = res.data;
  })
}
const restartForm = ref({
  queue: '',//模型队列
  source:{
    cpu: 1,
    gpu: 1,
    memory: 100
  },
  is_auto_stop: false,
  stop_in_seconds: '',
  is_fail_restart: false,
  restartNum: '',
})

const pageData = dataSetStore().pageData;
function sizeChange(pageSize:any) {
  dataSetStore().setPageData(1);
  dataSetStore().setPageSizeData(pageSize);
  getDataList()
}
function changePage(currentPage:any){
  dataSetStore().setPageData(currentPage);
  getDataList()
}
const runId = ref();
const modelId = ref();
const restartDialogShow = ref(false);
// const filterTableData = computed(() =>
//   labelAssignData.value.results.filter(
//     (data) =>
//       !searchName.value ||
//       data.title.toLowerCase().includes(searchName.value.toLowerCase()) ||
//       data.id.toString().toLowerCase().includes(searchName.value.toLowerCase())
//
//   )
// )
onMounted(() => {
  // 通过store.quickStart.quickFlow判断是否显示快速入门提示
  if (store.quickStart.quickFlow) {
    store.setQuickStart({
      tipsPopup: true,
      quickFlow: true,
      flowNumber: store.quickStart.flowNumber
    })
  }
});
showUserStore.addObserver(webSocketConnect);
function webSocketConnect(message: string) {
  if (message) {
    getDataList();
  }
}
function filterDataset(){
  dataSetStore().setPageData(1);
  getDataList()
};


//重启
function restartDialog () {
  restartDialogShow.value = true;
}
//重启弹框取消
function restartDialogForm () {
  restartDialogShow.value = false;
}
//重启弹框重启
function restartDialogSubmitForm () {
  restartDialogShow.value = false;
}

getDataList()
function getDataList() {
  loading.value = true;
  let obj:any = {}
  if( typeValue.value != '' ) obj.status = typeValue.value;
  if( searchName.value != '' ) obj.keyword = searchName.value;
  obj = Object.assign(obj, pageData);
  getAllRunsList(projectId,obj).then((res: any) => {
    labelAssignData.value = res.data;
  }).finally(() => {
    loading.value = false
  })
}
function toCreatePage() {
  modelStore().setShowModelId(0);
  router.push({ name: 'model-manage-create', params: { project_id: projectId } })
}

// 确认删除弹窗
function openDeleteBox(model_id: number, run_id: number) {
  runId.value = run_id
  modelId.value = model_id
  dialogDeleteData.value = true
}
function deleteData() {
  dialogDeleteData.value = false
  deleteRuns(projectId, modelId.value, runId.value).then((res: any) => {
    ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    })
  }).finally(() => {
    getDataList()
  }).catch((error) => {
    console.log(error)
  })
}
function toDetailPage(model_id: number, run_id: number) {
  const dataSetObj = modelStore()
  dataSetObj.dataset(model_id)
  dataSetObj.dataRunsIdset(run_id)
  router.push({ name: 'runs-detail', query: { project_id: projectId } })
}
function stopRunsFun(run_id: number) {
  ElMessageBox.confirm('确定停止该训练任务吗？', '停止任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    stopRuns(projectId, run_id).then(() => {
      ElMessage.success('停止训练成功！')
      getDataList()
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    console.log('cancel delete')
  })
}
</script>

<style scoped lang="scss">
:deep(.el-dialog__body){
  padding: 0!important;
}
:deep(.el-dialog__header){
  border-bottom: 1px solid red;
}
.restartWrap{
  margin-top: 20px;
  .restartFormBox{
    margin: 10px 0 0 40px;
  }
  .cpuDataBox{
    margin-bottom: 0;
  }
  .tip{
    display: inline-block;
    color: #999999;
    font-weight: 400;
    font-size: 14px;
    margin: 10px 0 10px 40px;
  }
  .borderWrap{
    display: flex;
    flex-direction: row;
    width: 90%;
    height: 40px;
    padding: 9px 16px;
    margin-left: 5%;
    border: 1px solid #FFA940;
    border-radius: 2px;
    background: #FFFBE6;
    .titleIcon{
      margin-top: 3px;
      margin-right: 5px;
      font-size: 17px;
      color: #FFA940;
    }
    .text{
      font-weight: 400;
      font-size: 14px;
      color: #666666;
    }
  }
  .colorBox{
    margin-left: 10px;
  }
}
//超出显示小圆点 start
.overFlowEllipsis {
  width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  text-align: left;
}
// end
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;
    ::v-deep .el-breadcrumb{
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      position: relative;
      display: flex;
      align-items: center;
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
      .icon{
        position: absolute;
        left: 90px;
        top: 22px;
        width: 17px;
      }
      .text{
        position: absolute;
        left: 104px;
        top: 19px;
        font-size: 12px;
        color: #3d5ce4;
        font-weight: 400;
        cursor: pointer;
      }
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .searchWrap{
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
//输入框placeholder样式
::v-deep .el-input__inner {
  &::placeholder {
    color: #ccc;
    font-size: 14px;
  }
  &::-webkit-input-placeholder {
    /* WebKit browsers 适配谷歌 */
    color: #ccc;
    font-size: 14px;
  }
  &:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 适配火狐 */
    color: #ccc;
    font-size: 14px;
  }
  &::-moz-placeholder {
    /* Mozilla Firefox 19+ 适配火狐 */
    color: #ccc;
    font-size: 14px;
  }
  &:-ms-input-placeholder {
    /* Internet Explorer 10+  适配ie*/
    color: #ccc;
    font-size: 14px;
  }
}
//分页输入框跳转不限制
::v-deep disabled,::v-deep  .disabled *, ::v-deep [disabled],::v-deep [disabled] * {
  outline: 10px !important;
  cursor: pointer !important;
}
//点击下拉框，去掉输入框蓝色高亮显示
:deep(.el-input){
  --el-input-focus-border:#fff;
  --el-input-transparent-border: 0 0 0 0px;
  --el-input-border-color:var(--el-border-color);
  --el-input-hover-border:0px !important;
  --el-input-hover-border-color:var(--el-border-color);
  --el-input-focus-border-color:var(--el-border-color);
  --el-input-clear-hover-color:var(--el-border-color);
}
</style>
